<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { GetData, PostAudit } from '@/api/modules/refundApply.ts'
import PageNumber from '@/store/modules/PageNumberCache'

const PageNumberCache = PageNumber()
// 导航栏
const orderFlag = ref('')
// 导航栏切换时的回调
function handleSelect(key: string) {
  // console.log(key)
  orderFlag.value = key
  GetDataList()
}

const findTypeArr = [
  {
    key: '0',
    label: '退款',
  },
  {
    key: '1',
    label: '极速退款',
  },
  {
    key: '2',
    label: '后台退款',
  },
  // {
  //   value: '3',
  //   label: '退货退款',
  // },
  // {
  //   value: '4',
  //   label: '其他',
  // },
]
// 查询的表单
const findFrom = reactive({
  OutTradeNo: '',
  TransactionId: '',
  TuikuanWldh: '',
  UserId: '',
  ReceiverName: '',
  ReceiverTelNumber: '',
  refundType: '',
})

let PageSize = 20
const total = ref(0) // 总数据数
const orderList: any = ref([])

// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 获取数据
async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(orderFlag.value && { Flag: orderFlag.value }),
    ...(findFrom.OutTradeNo && { OutTradeNo: findFrom.OutTradeNo }),
    ...(findFrom.TransactionId && { TransactionId: findFrom.TransactionId }),
    ...(findFrom.TuikuanWldh && { TuikuanWldh: findFrom.TuikuanWldh }),
    ...(findFrom.UserId && { UserId: findFrom.UserId }),
    ...(findFrom.ReceiverName && { ReceiverName: findFrom.ReceiverName }),
    ...(findFrom.ReceiverTelNumber && { ReceiverTelNumber: findFrom.ReceiverTelNumber }),
    ...(findFrom.refundType && { refundType: findFrom.refundType }),
  }
  await GetData(params).then((res: any) => {
    if (res.succeeded) {
      total.value = res.data.total
      orderList.value = res.data.items
      // orderList.value.forEach((item: any) => {
      //   item.refundFee = toNumber(item.refundFee) / 100
      //   item.totalFee = toNumber(item.totalFee) / 100
      // })
    }
  })
}
// 审核
function Audit(outTradeNo: string, isPass: boolean) {
  const params = {
    outTradeNo,
    isPass,
  }
  PostAudit(params).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('操作成功')
      GetDataList(PageNumberCache.GetRefundApplyPage(), PageSize)
    }
    else {
      if (typeof res.errors === 'string') {
        ElMessage.error(`修改失败。${res.errors}`)
      }
      else {
        let errorStr = ''
        for (const key in res.errors) {
          errorStr += `${key}：${res.errors[key]}；`
        }
        ElMessage.error(`修改失败。${errorStr}`)
      }
    }
  })
}

// 通过
function Pass(item: any) {
  ElMessageBox.confirm(
    `确定通过该退款吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      Audit(item.outTradeNo, true)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
// 驳回
function Reject(item: any) {
  ElMessageBox.confirm(
    `确定要驳回该退款吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      Audit(item.outTradeNo, false)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNumberCache.SetRefundApplyPage(val)
}

onMounted(() => {
  GetDataList(PageNumberCache.GetRefundApplyPage())
})
</script>

<template>
  <div>
    <el-menu :default-active="orderFlag" mode="horizontal" @select="handleSelect">
      <el-menu-item index="">
        全部
      </el-menu-item>
      <el-menu-item index="-1">
        待审核
      </el-menu-item>
      <el-menu-item index="-2">
        审核不通过
      </el-menu-item>
      <el-menu-item index="0">
        审核通过待打款
      </el-menu-item>
      <el-menu-item index="-10">
        后台退款待打款
      </el-menu-item>
      <el-menu-item index="1">
        审核通过退款完成
      </el-menu-item>
    </el-menu>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="订单编号">
                <el-input v-model="findFrom.OutTradeNo" placeholder="请输入订单编号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="微信支付交易ID">
                <el-input v-model="findFrom.TransactionId" placeholder="请输入微信支付交易ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="退货退款物流单号">
                <el-input v-model="findFrom.TuikuanWldh" placeholder="请输入退货退款物流单号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入收货人ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="收货人">
                <el-input v-model="findFrom.ReceiverName" placeholder="请输入收货人" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="收货人手机号">
                <el-input v-model="findFrom.ReceiverTelNumber" placeholder="请输入收货人手机号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="退款类型">
                <el-select v-model="findFrom.refundType" placeholder="请选择退款类型" clearable>
                  <el-option
                    v-for="item in findTypeArr" :key="item.key" :label="item.label" :value="item.label"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="body">
        <el-card v-for="item in orderList" :key="item.orderNum" class="order" shadow="never">
          <template #header>
            <div>
              <span style="margin-right: 10px;">退款信息</span>
            </div>
          </template>
          <!-- 基本信息 -->
          <div style="display: grid; grid-template-columns: 1fr 4fr 1fr;">
            <div>
              <el-image :src="item.subscriberInfo?.userAvatar" fit="fill" style="width: 100px; height: 100px;">
                <template #error>
                  <div class="image-slot">
                    <el-icon><IconPicture /></el-icon>
                  </div>
                </template>
              </el-image>
              <el-descriptions class="margin-top" :column="1">
                <el-descriptions-item label="用户ID:">
                  {{ item.subscriberInfo?.userId }}
                </el-descriptions-item>
                <el-descriptions-item label="用户昵称:">
                  {{ item.subscriberInfo?.userNickName }}
                </el-descriptions-item>
                <el-descriptions-item label="授权手机号:">
                  {{ item.subscriberInfo?.userPhone }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <el-descriptions class="margin-top" :column="2">
              <el-descriptions-item label="订单编号">
                {{ item.outTradeNo }}
              </el-descriptions-item>
              <el-descriptions-item label="微信支付交易Id">
                {{ item.transactionId }}
              </el-descriptions-item>
              <el-descriptions-item label="外部退款单号">
                {{ item.outRefundNo }}
              </el-descriptions-item>
              <el-descriptions-item v-if="item.tuikuanWldh" label="退款物流单号">
                {{ item.tuikuanWldh }}
              </el-descriptions-item>
              <el-descriptions-item label="合计金额">
                {{ item.totalFee }}
              </el-descriptions-item>
              <el-descriptions-item label="实际退款金额">
                {{ item.refundFee }}
              </el-descriptions-item>
              <el-descriptions-item label="代金券退款金额">
                {{ item.couponRefundFee }}
              </el-descriptions-item>
              <el-descriptions-item v-if="item.refundChannel" label="退款渠道">
                {{ item.refundChannel }}
              </el-descriptions-item>
              <el-descriptions-item v-if="item.refundStatus" label="退款状态">
                {{ item.refundStatus }}
              </el-descriptions-item>
              <el-descriptions-item v-if="item.errCodeDes" label="退款失败错误码">
                {{ item.errCodeDes }}
              </el-descriptions-item>
            </el-descriptions>
            <div class="relative">
              <el-descriptions class="margin-top" :column="1">
                <el-descriptions-item label="申请时间">
                  {{ item.addTime }}
                </el-descriptions-item>
                <el-descriptions-item label="最后更新时间">
                  {{ item.updateTime }}
                </el-descriptions-item>
              </el-descriptions>
              <div v-if="item.flag === -1" class="absolute bottom-0 right-10">
                <el-button type="success" @click="Pass(item)">
                  通过
                </el-button>
                <el-button type="danger" @click="Reject(item)">
                  驳回
                </el-button>
              </div>
            </div>
          </div>
          <template #footer>
            类型：{{ item.tuikuanDesp }}
          </template>
        </el-card>
      </div>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 8fr 1fr;
  margin-top: 25px;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.body {
  padding: 0 10px;

  .order {
    box-sizing: border-box;
    margin: 10px 0;
    background-color: white;
    border: 1px solid rgb(190 190 190);

    header {
      padding: 15px 5px;
      font-size: 19px;

      /* border-bottom: 1px solid rgb(228 228 228); */
    }
  }
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 30px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);

  .el-icon {
    font-size: 30px;
  }
}
</style>
